*------------------------------------------------------------------------------
* Table A3. multilevel models for political homophily (dyadic levels)
* generate numbers for Figure 4 + 5
* also see PI_figure_homophily_trends.R | 
*==============================================================================

preserve

keep if expand_new == 0

keep r_age r_educ r_female r_race r_married r_working r_partyid7 same?_pid3 a?_partyid3 pid3 k_* /*
*/ year ayear n_size id a0_rel a*_relative a?_spouse a?_parent a?_sibling a?_child  a?_cowork a?_neighbor a?_friend a?_advisor a?_other a?_othfam /*
*/ a*_vote_same_a a*_vote_same a?_same_church a?_family a?_closefriend a?_unrelated imp_name 

replace ayear = 2016 if ayear == 2017 

egen year_id = group(year id)
drop if year_id == .
egen ayear_id = group(ayear imp_name id)

reshape long a@_relative same@_pid3 a@_vote_same_a a@_vote_same a@_same_church a@_partyid3 /*
*/ a@_spouse a@_parent a@_sibling a@_child a@_othfam a@_cowork a@_neighbor a@_friend a@_advisor a@_other a@_family a@_closefriend a@_unrelated,i(ayear_id) j(order)

* after reshape data; recover the year 
gen byear = year 
replace byear = 2017 if k_imp == 0 

* generate weight based on the network size 
gen ipw = 1/n_size 

gen a_homophily = same_pid3 
replace a_homophily = a_vote_same if ~missing(a_vote_same)

drop if missing(a_homophily)

* for figure 5
mean a_homophily [pw=ipw], over(ayear imp_name)

* for figure 6
mean a_homophily [pw=ipw], over(ayear), if a_relative == 0
mean a_homophily [pw=ipw], over(ayear), if a_relative == 1

xtset ayear 
estimates clear
xtlogit a_homophily r_age r_educ r_female i.r_race r_married r_working b4.r_partyid7 order b2016.year if imp_name == 0
estimates store model1
xtlogit a_homophily r_age r_educ r_female i.r_race r_married r_working b4.r_partyid7 order b2016.year if imp_name == 1
estimates store model2

esttab * using "./tables/table_xtlogit_homophily.csv", csv replace star(+ 0.1 * 0.05) se nogap label 

restore 
